package com.bim.fallback;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 公共服务回退类
 * @author hxw
 */
public class CommonProviderfallback implements FallbackProvider {

	@Override
	public String getRoute() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		return new ClientHttpResponse() {
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.SERVICE_UNAVAILABLE;
			}
			@Override
			public int getRawStatusCode() throws IOException {
				return this.getStatusCode().value();
			}
			@Override
			public String getStatusText() throws IOException {
				return this.getStatusCode().getReasonPhrase();
			}
			@Override
			public void close() {

			}
			@Override
			public InputStream getBody() throws IOException {
				JSONObject json = new JSONObject();
				json.put("status", HttpStatus.SERVICE_UNAVAILABLE.value());
				json.put("msg", HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase());
				return new ByteArrayInputStream(json.toJSONString().getBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				/**设置headers*/
				HttpHeaders headers = new HttpHeaders();
				MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
				headers.setContentType(mt);
				return headers;
			}
		};
	}
}
